package concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;


/**
 * acquire() 尝试获取一个许可，若无法获得，线程会等待，
*            直到有线程释放许可或者当前线程被中断
 * acquireUninterruptibly() 不响应中断
 * tryAcquire() 尝试获取一个许可，成功返回true，否则false
 * release() 释放许可
 */
public class SemapDemo implements Runnable {

    final Semaphore semaphore = new Semaphore(5);

    @Override
    public void run() {
        try {
            semaphore.acquireUninterruptibly();
            Thread.sleep(2000);
            System.out.println(Thread.currentThread().getId() + " :done!");
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(20);
        final SemapDemo demo = new SemapDemo();
        for (int i = 0; i <20; i++) {
            exec.execute(demo);
        }
    }

}
